var elementCtrl = {
	findParent: function(el, tag){
		while(el && el.tagName != tag){
			el = el.parentNode;
		}
		return el;
	},
	movePre: function(el){
		var parent = el.parentNode;
		var els = parent.children;
		var beforeElement = null;
		for (var i = 0, l = els.length; i < l; i++) {
			if (el === els[i]) {
				break;
			} else {
				beforeElement = els[i];
			}
		}
		parent.insertBefore(el, beforeElement);
	},
	moveNext: function(el){
		var parent = el.parentNode;
		var els = parent.children;
		var beforeElement = null;
		for (var i = els.length; i > -1; i--) {
			if (el === els[i]) {
				break;
			} else {
				beforeElement = els[i + 1];
			}
		}
		if (beforeElement) {
			parent.insertBefore(el, beforeElement);
		} else {
			parent.appendChild(el);
		}
	}
};
var tableCtrl = {
	removeRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		var table = elementCtrl.findParent(el, 'TABLE');
		table.deleteRow(row.rowIndex);
	},
	insertRow: function(html){
		var table = document.getElementsByTagName('table')[0];
		var tbody = table.tBodies[0];
		var row = tbody.insertRow();
		row.innerHTML = html;
	},
	upRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		elementCtrl.movePre(row);
	},
	downRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		elementCtrl.moveNext(row);
	}
};
var pageCtrl = {
	toggle: function(){
		var container = document.getElementById('formContainer');
		if (container.className === 'hidden') {
			container.className = 'popupLayer';
		} else {
			container.className = 'hidden';
		}
	},
	addData: function(){
		var form = document.forms[0];
		var name = form.productName.value;
		var price = form.productPrice.value;
		var count = form.productCount.value;
		var html = [
			'<td>', name, '</td>',
			'<td>', price, '</td>',
			'<td>', count, '</td>',
			'<td>',
			'<button type="button" onclick="tableCtrl.removeRow(this);">삭제</button>',
			'<button type="button" onclick="tableCtrl.upRow(this);">▲</button>',
			'<button type="button" onclick="tableCtrl.downRow(this);">▼</button>',
			'</td>'
		].join('');
		tableCtrl.insertRow(html);
		this.toggle();
	}
};
